#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libunistring_libunistring_func_004.py
@Time:      2024/02/22 14:20:00
@Author:    suomengjun
@Version:   1.0
@Contact:   smj01095381@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    suomengjun
"""

import os
from common.basetest import LocalTest


class Test(LocalTest):
    """
    See tc_libunistring_libunistring_func_004.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "gcc libunistring libunistring-devel"}

    def setUp(self):
        super().setUp(self.PARAM_DIC)
        code_p = os.path.dirname(os.path.abspath(__file__))
        code = r'''cat > test_unistring_utf8_to_utf16.c << EOF
#include <unistr.h>
#include <stdio.h>
#include <string.h>
#include "CODE_P/verify_utf8.h"

int main(int argc, char *argv[]) {
    // 需要至少一个参数
    if (argc < 2) {
        printf("Error:At least one parameter is required,but there are no parameters.\n");
        return 1;
    }
    const char *cur_str = argv[1];
    if (!isValidUtf8(cur_str)) {
        printf("Error: The string is NOT valid UTF-8--->(%s)\n", cur_str);
        return 1;
    } 

    // UTF-8转UTF-16
    uint8_t *utf8_string = (uint8_t *)cur_str;
    size_t utf8_length = strlen(cur_str);
    uint16_t utf16_buffer[64] = {0};
    size_t utf16_length = 64;

    if (u8_to_u16(utf8_string, utf8_length, utf16_buffer, &utf16_length) == NULL) {
        printf("Failed to convert UTF-8 string to UTF-16\n");
        return 1;
    }

    // 打印转换结果
    printf("STR: %s \nUTF-16 length: %zu\n", cur_str, utf16_length);
    for (size_t i = 0; i < utf16_length; ++i) {
        printf("%04x ", utf16_buffer[i]);
    }
    printf("\n");
    return 0;
}
EOF'''
        self.cmd(code)
        self.cmd(f"sed -i 's|CODE_P|{code_p}|g' test_unistring_utf8_to_utf16.c")
        self.cmd(f"gcc -o test_unistring_utf8_to_utf16 test_unistring_utf8_to_utf16.c {code_p}/verify_utf8.c -lunistring")

    def test(self):
        self.cmd("./test_unistring_utf8_to_utf16 龙蜥")
        self.cmd("./test_unistring_utf8_to_utf16 龙蜥社区")
        self.cmd("./test_unistring_utf8_to_utf16 longxi")
        self.cmd("./test_unistring_utf8_to_utf16 longxishequ")
        self.cmd("./test_unistring_utf8_to_utf16 0123456")

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        for file in ['test_unistring_utf8_to_utf16', 'test_unistring_utf8_to_utf16.c']:
            if os.path.exists(file):
                self.cmd(f"rm -rf {file}")
